# bloggerdotcom.py
# Original Author: Amar Zumkhawala (amarzumkhawala@gmail.com)
# Project URL - http://code.google.com/p/feedflare-categories
# Distributed under Apache License 2.0
#
# $Revision: 20 $, $Date: 2009-01-02 09:11:18 +0000 (Fri, 02 Jan 2009) $
# $Author: amarzumkhawala $

import re
import logging
from google.appengine.api import urlfetch
from blogservice import AbstractBlogService, BlogEntry

"""
Blogger.com implementation of AbstractBlogService.
"""
class BloggerDotComService(AbstractBlogService):
  def __init__(self, id):
    self._blogEntry = self.parse(id)
  
  def blogEntry(self):
    return self._blogEntry

  """Fetch the atom entry xml for the blog entry"""
  def fetchBlogXml(self, blogEntry):
      blogId = blogEntry.blogger_blogId
      postId = blogEntry.blogger_postId
      postfeedurl = "http://www.blogger.com/feeds/" + blogId + "/posts/default/" + postId + "?v=2"      
      logging.info("blogger.com urlfetch: " + postfeedurl);

      try :
        result = urlfetch.fetch(postfeedurl)
      except Exception:
        # raise new exception with more details
        logging.exception("exception during url fetch")
        raise Exception("urlfetch for feed " + postfeedurl + " resulted in exception")
 
      if result.status_code != 200:
        raise Exception("Http error in url fetch: " + str(result.status_code))

      atomEntryXml = result.content
      return atomEntryXml

  """Build url to webpage that searches the blog for posts labeled with the 
  first found category.  The blogger.com /search/label url only supports 
  one category.   
  """ 
  def getBlogSearchByCategoryUrl(self, atomEntry):
    categories = atomEntry.categories()
    blogSearchByCategoryUrl = ""
    if len(categories) > 0:
      blogSearchByCategoryUrl = atomEntry.blogUrl() + "search/label/" + atomEntry.categories()[0]
    return blogSearchByCategoryUrl

  """Parse the given blogger.com atom post id for the blog id and post id"""
  def parse(self,id):
    if len(id) == 0:
      raise Exception("No id parameter given")

    blogEntry = BlogEntry()
    blogEntry.setAtomId(id)

    idparts=id.split(',')
    p = re.match(r"\S+blog-(\d+)\.post-(\d+)",idparts[1])
    if p == None:
      raise Exception("Could not parse given blogger.com post id: " + id)

    blogId=p.group(1)
    if len(blogId) == 0:
      raise Exception("Could not find blog id in " + id)

    postId=p.group(2)
    if len(postId) == 0:
      raise Exception("Could not find post id in " + id)

    blogEntry.blogger_blogId = blogId
    blogEntry.blogger_postId = postId 

    return blogEntry
